package com.warmheart.controller.access;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.warmheart.base.annotation.Auth;
import com.warmheart.base.annotation.Duplicate;
import com.warmheart.base.controller.BaseController;
import com.warmheart.base.page.PageInfo;
import com.warmheart.core.enums.ResultCode;
import com.warmheart.core.result.CommonResult;
import com.warmheart.core.util.OperatorUtil;
import com.warmheart.core.util.ParamMapUtil;
import com.warmheart.entity.access.AccessLog;
import com.warmheart.service.access.IAccessLogService;

/**
 * 
 * @ClassName: AccessLogController
 * @Description: 访问记录控制器
 * @author ZhangJianyang
 * @date 2025年06月16日 下午13:05:35
 *
 */
@RestController
@RequestMapping("/access/accessLog")
public class AccessLogController extends BaseController {
    
    private static final Logger logger = LoggerFactory.getLogger(AccessLogController.class);

    // 注入访问记录service
    @Autowired(required = false)
    private IAccessLogService accessLogService;

    /**
     * 
     * @Title: listData
     * @Description: 查询访问记录列表数据
     * @author ZhangJianyang
     * @date 2025年06月16日 下午13:05:35
     * @param request
     * @param response
     * @throws Exception
     */
    @Auth(verifyLogin = true)
    @RequestMapping("/listData")
    public CommonResult<Map<String, Object>> listData(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 参数数据
        Map<String, Object> jsonMap = getJsonMap(request);
        
        // 返回结果
        Map<String, Object> resultMap = new HashMap<String, Object>();
        
        // 参数对象
        AccessLog accessLog = new AccessLog();
        
        // 每页记录数
        Integer pageSize = ParamMapUtil.getInteger(jsonMap, "pageSize");
        if (pageSize == null) {
            return CommonResult.failed(ResultCode.PARAM_EMPTY, "每页记录数不能为空");
        }
        if (pageSize <= 0) {
            return CommonResult.failed(ResultCode.PARAM_INVALID, "每页记录数必须大于0");
        }
        accessLog.setPageSize(pageSize);

        // 页码
        Integer pageId = ParamMapUtil.getInteger(jsonMap, "pageId");
        if (pageId == null) {
            return CommonResult.failed(ResultCode.PARAM_EMPTY, "页码不能为空");
        }
        if (pageId <= 0) {
            return CommonResult.failed(ResultCode.PARAM_INVALID, "页码必须大于0");
        }
        accessLog.setPageId(pageId);

        // 查询列表
        PageInfo<AccessLog> pageInfo = this.accessLogService.queryByList(accessLog);

        List<AccessLog> dataList = pageInfo.getData();
        Map<String,Object> pageMap = new HashMap<String,Object>();
        List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
        if (dataList != null && dataList.size() > 0) {
            
            // 整理返回数据
            for (AccessLog tempData : dataList) {
                Map<String, Object> tempMap = new HashMap<String, Object>();
                tempMap.put("id", tempData.getId());
                tempMap.put("userId", tempData.getUserId());
                tempMap.put("resourceType", tempData.getResourceType());
                tempMap.put("resourceId", tempData.getResourceId());
                tempMap.put("action", tempData.getAction());
                tempMap.put("ipAddress", tempData.getIpAddress());
                tempMap.put("userAgent", tempData.getUserAgent());
                tempMap.put("details", tempData.getDetails());
                tempMap.put("cstCreate", tempData.getCstCreate());
                mapList.add(tempMap);
            }
        }
        pageMap.put("dataList", mapList);
        pageMap.put("rowCount", pageInfo.getPager().getRowCount());
        pageMap.put("pageCount", pageInfo.getPager().getPageCount());
        resultMap.put("pageMap", pageMap);
        return CommonResult.success("分页查询访问记录数据成功", resultMap);
    }

    /**
     * 
     * @Title: update
     * @Description: 修改访问记录数据进入页面
     * @author ZhangJianyang
     * @date 2025年06月16日 下午13:05:35
     * @param request
     * @param response
     * @throws Exception
     */
    @Auth(verifyLogin = true)
    @RequestMapping("/update")
    public CommonResult<Map<String, Object>> update(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 参数数据
        Map<String, Object> jsonMap = getJsonMap(request);
        
        // 返回结果
        Map<String, Object> resultMap = new HashMap<String, Object>();
        
        // 主键ID
        Integer id = ParamMapUtil.getInteger(jsonMap, "id");
        if (id == null) {
            return CommonResult.failed(ResultCode.PARAM_EMPTY, "该访问记录ID不可为空");
        }

        // 校验是否存在
        AccessLog checkAccessLog = accessLogService.queryById(id);
        if (checkAccessLog == null) {
            return CommonResult.failed(ResultCode.PARAM_INVALID, "该访问记录不存在");
        }
        Map<String, Object> tempMap = new HashMap<String, Object>();
        tempMap.put("id", checkAccessLog.getId());
        tempMap.put("userId", checkAccessLog.getUserId());
        tempMap.put("resourceType", checkAccessLog.getResourceType());
        tempMap.put("resourceId", checkAccessLog.getResourceId());
        tempMap.put("action", checkAccessLog.getAction());
        tempMap.put("ipAddress", checkAccessLog.getIpAddress());
        tempMap.put("userAgent", checkAccessLog.getUserAgent());
        tempMap.put("details", checkAccessLog.getDetails());
        tempMap.put("cstCreate", checkAccessLog.getCstCreate());
        resultMap.put("dataMap", tempMap);
        return CommonResult.success("获取访问记录数据成功", resultMap);
    }

    /**
     * 
     * @Title: addSave
     * @Description: 添加保存访问记录数据
     * @author ZhangJianyang
     * @date 2025年06月16日 下午13:05:35
     * @param request
     * @param response
     * @throws Exception
     */
    @Auth(verifyLogin = true)
    @Duplicate(validate = true)
    @RequestMapping("/addSave")
    public CommonResult<Map<String, Object>> addSave(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 参数数据
        Map<String, Object> jsonMap = getJsonMap(request);
        
        // 数据对象
        AccessLog accessLog = new AccessLog();
        
        // 用户ID
        Integer userId = ParamMapUtil.getInteger(jsonMap, "userId");
        if (userId != null) {
            accessLog.setUserId(userId);
        }
        
        // 资源类型
        String resourceType = ParamMapUtil.getString(jsonMap, "resourceType");
        if (StringUtils.isNotBlank(resourceType)) {
            accessLog.setResourceType(resourceType);
        }
        
        // 资源ID
        Integer resourceId = ParamMapUtil.getInteger(jsonMap, "resourceId");
        if (resourceId != null) {
            accessLog.setResourceId(resourceId);
        }
        
        // 操作类型
        String action = ParamMapUtil.getString(jsonMap, "action");
        if (StringUtils.isNotBlank(action)) {
            accessLog.setAction(action);
        }
        
        // IP地址
        String ipAddress = ParamMapUtil.getString(jsonMap, "ipAddress");
        if (StringUtils.isNotBlank(ipAddress)) {
            accessLog.setIpAddress(ipAddress);
        }
        
        // 用户代理
        String userAgent = ParamMapUtil.getString(jsonMap, "userAgent");
        if (StringUtils.isNotBlank(userAgent)) {
            accessLog.setUserAgent(userAgent);
        }
        
        // 操作详情
        String details = ParamMapUtil.getString(jsonMap, "details");
        if (StringUtils.isNotBlank(details)) {
            accessLog.setDetails(details);
        }

        try {
            OperatorUtil.addOper(accessLog);
            accessLogService.add(accessLog);
        } catch (Exception e) {
            // 打印错误日志
            logger.error("添加访问记录失败", e);
            return CommonResult.failed(ResultCode.BUSINESS_ERROR, "添加访问记录失败");
        }

        return CommonResult.success("添加访问记录成功");
    }

    /**
     * 
     * @Title: updateSave
     * @Description: 修改保存访问记录数据
     * @author ZhangJianyang
     * @date 2025年06月16日 下午13:05:35
     * @param request
     * @param response
     * @throws Exception
     */
    @Auth(verifyLogin = true)
    @Duplicate(validate = true)
    @RequestMapping("/updateSave")
    public CommonResult<Map<String, Object>> updateSave(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, Object> jsonMap = getJsonMap(request);
        
        // 主键ID
        Integer id = ParamMapUtil.getInteger(jsonMap, "id");
        if (id == null) {
            return CommonResult.failed(ResultCode.PARAM_EMPTY, "该访问记录ID不可为空");
        }

        // 是否存在校验
        AccessLog checkAccessLog = accessLogService.queryById(id);
        if (checkAccessLog == null) {
            return CommonResult.failed(ResultCode.PARAM_INVALID, "该访问记录不存在");
        }

        
        // 用户ID
        Integer userId = ParamMapUtil.getInteger(jsonMap, "userId");
        if (userId != null) {
            checkAccessLog.setUserId(userId);
        }
        
        // 资源类型
        String resourceType = ParamMapUtil.getString(jsonMap, "resourceType");
        if (StringUtils.isNotBlank(resourceType)) {
            checkAccessLog.setResourceType(resourceType);
        }
        
        // 资源ID
        Integer resourceId = ParamMapUtil.getInteger(jsonMap, "resourceId");
        if (resourceId != null) {
            checkAccessLog.setResourceId(resourceId);
        }
        
        // 操作类型
        String action = ParamMapUtil.getString(jsonMap, "action");
        if (StringUtils.isNotBlank(action)) {
            checkAccessLog.setAction(action);
        }
        
        // IP地址
        String ipAddress = ParamMapUtil.getString(jsonMap, "ipAddress");
        if (StringUtils.isNotBlank(ipAddress)) {
            checkAccessLog.setIpAddress(ipAddress);
        }
        
        // 用户代理
        String userAgent = ParamMapUtil.getString(jsonMap, "userAgent");
        if (StringUtils.isNotBlank(userAgent)) {
            checkAccessLog.setUserAgent(userAgent);
        }
        
        // 操作详情
        String details = ParamMapUtil.getString(jsonMap, "details");
        if (StringUtils.isNotBlank(details)) {
            checkAccessLog.setDetails(details);
        }

        try {
            OperatorUtil.updateOper(checkAccessLog);
            accessLogService.updateIncludeAll(checkAccessLog);
        } catch (Exception e) {
            // 打印错误日志
            logger.error("修改访问记录失败", e);
            return CommonResult.failed(ResultCode.BUSINESS_ERROR, "修改访问记录失败");
        }

        return CommonResult.success("修改访问记录成功");
    }

    /**
     * 
     * @Title: delete
     * @Description: 删除访问记录数据
     * @author ZhangJianyang
     * @date 2025年06月16日 下午13:05:35
     * @param request
     * @param response
     * @throws Exception
     */
    @Auth(verifyLogin = true)
    @RequestMapping("/delete")
    public CommonResult<Map<String, Object>> delete(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, Object> jsonMap = getJsonMap(request);
        Integer id = ParamMapUtil.getInteger(jsonMap, "id");
        if (id == null) {
            return CommonResult.failed(ResultCode.PARAM_EMPTY, "该访问记录ID不可为空");
        }

        // 是否存在校验
        AccessLog checkAccessLog = accessLogService.queryById(id);
        if (checkAccessLog == null) {
            return CommonResult.failed(ResultCode.PARAM_INVALID, "该访问记录不存在");
        }

        try {
            accessLogService.deleteById(checkAccessLog.getId());
        } catch (Exception e) {
            // 打印错误日志
            logger.error("删除访问记录失败", e);
            return CommonResult.failed(ResultCode.BUSINESS_ERROR, "删除访问记录失败");
        }

        return CommonResult.success("删除访问记录成功");
    }
}
